from rest_framework import serializers
from answers.models import Reply, Question
from users.models import User


class PublishQuestionSerializers(serializers.ModelSerializer):
    '''发布问题序列化器类'''

    class Meta:

        model = Question

        fields = ('content','labels','title','user')

        extra_kwargs = {
            'user':{"write_only":True,"required":True},
            'content':{"required": True},
            'labels':{"required": True},
            'title':{"required": True}
        }
#============================================================================
# 问题详情序列化器类

class ObtainDetailCommentQuestionUserSerializers(serializers.ModelSerializer):


    class Meta:

        model = User

        fields = ('id','username','avatar')


class ObtainDetailAnswerQuestionSubsSerializers(serializers.ModelSerializer):

    user = ObtainDetailCommentQuestionUserSerializers(read_only=True)

    class Meta:

        model = Reply

        exclude = ('updatetime', 'type','problem','parent')



class ObtainDetailAnswerQuestionSerializers(serializers.ModelSerializer):
    '''answer_question'''
    subs = ObtainDetailAnswerQuestionSubsSerializers(read_only=True,many=True)

    user = ObtainDetailCommentQuestionUserSerializers(read_only=True)

    class Meta:

        model = Reply

        exclude = ('updatetime', 'type')



class ObtainDetailCommentQuestionSerializers(serializers.ModelSerializer):

    user = ObtainDetailCommentQuestionUserSerializers(read_only=True)

    subs = serializers.StringRelatedField(read_only=True,many=True)

    content = serializers.CharField(read_only=True)

    class Meta:

        model = Reply

        exclude = ('updatetime', 'type')



class ObtainDetailQuestionSerializers(serializers.ModelSerializer):

    labels = serializers.StringRelatedField(read_only=True,many=True)

    comment_question = ObtainDetailCommentQuestionSerializers(read_only=True,source='replies',many=True)

    answer_question = ObtainDetailAnswerQuestionSerializers(read_only=True,source='replies',many=True)

    class Meta:

        model = Question

        fields = ('id','createtime','labels','reply','replyname','replytime','title',
                  'unuseful_count','useful_count','user','visits','content',
                  'comment_question','answer_question')

#========================================================================================

class ReplyQuestionSerializers(serializers.ModelSerializer):
    '''回答问题序列化器类'''
    content = serializers.CharField(required=True)

    class Meta:

        model = Reply

        fields = ('problem','type','user','parent','content')

        extra_kwargs = {
            "problem":{"required":True},
            "type": {"required": True},
            "user": {"required": True,"write_only":True}
        }


